package com.p7.notepad.app;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Window;

import com.p7.notepad.R;
import com.tools.s7.base.CompatActivity;

import butterknife.ButterKnife;

public abstract class BaseActivity extends CompatActivity {

    private static final int PERMISSION_REQUEST_CODE = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(getLayoutId());
        barUtils.setStatusBar(getResources().getColor(R.color.white), true);
        ButterKnife.bind(this);
        initEvents();
    }

    public abstract int getLayoutId();

    /**
     * 初始化事件
     */
    protected void initEvents() {}

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        doNext(requestCode, grantResults);
    }

    public void doNext(int requestCode, int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean isGranted = true;
            for (int result: grantResults){
                if(result != PackageManager.PERMISSION_GRANTED){
                    isGranted = false;
                }
            }
            if (isGranted) { //全部允许了
                onGranted();
            }
        }
    }

    protected void onGranted() {

    }


    String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA,
            Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO};

    public boolean checkPermission() {
        if(hasPermissions()){
            return true;
        } else {
            ActivityCompat.requestPermissions(this, perms, PERMISSION_REQUEST_CODE);
            return false;
        }
    }

    public boolean hasPermissions() {
        for (String perm : perms) {
            if(ContextCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED){
                return false;
            }
        }
        return true;
    }

}
